#!/bin/bash

# 日志函数
log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1"
}

# 检查并安装必要的工具
install_required_tools() {
    log "检查并安装必要的工具..."

    if ! command -v curl &> /dev/null; then
        log "curl 未安装，正在安装..."
        if [[ "$OSTYPE" == "linux-gnu"* ]]; then
            sudo apt-get update
            sudo apt-get install -y curl
        elif [[ "$OSTYPE" == "darwin"* ]]; then
            brew install curl
        else
            log "不支持的操作系统。请手动安装 curl。"
            exit 1
        fi
    fi

    if ! command -v jq &> /dev/null; then
        log "jq 未安装，正在安装..."
        if [[ "$OSTYPE" == "linux-gnu"* ]]; then
            sudo apt-get update
            sudo apt-get install -y jq
        elif [[ "$OSTYPE" == "darwin"* ]]; then
            brew install jq
        else
            log "不支持的操作系统。请手动安装 jq。"
            exit 1
        fi
    fi
}

# 下载并执行指定的脚本
download_and_execute_scripts() {
    local base_url="https://gitee.com/vangelisx/hs_shell/raw/main/src"  # 写死的基准 URL
    local scripts=("ops_down.sh" "git-to-master.sh" "git-merge-master.sh" "git-clone-group.sh")  # 在这里列出所有需要下载的脚本名称
    local download_dir="$HOME/Downloads"  # 用户的下载目录
    for script_name in "${scripts[@]}"; do
       local script_url="$base_url/$script_name"
       local script_path="$download_dir/$script_name"

       log "下载脚本 $script_url 到 $script_path ..."
       curl -# -o "$script_path" "$script_url"
       local script_name_no_ext="${script_name%.sh}"
        log "请求sudo权限将脚本复制到 /usr/local/bin 并赋予执行权限..."
        sudo cp "$script_path" "/usr/local/bin/$script_name_no_ext"
        sudo chmod +x "/usr/local/bin/$script_name_no_ext"
        log "脚本已下载并复制到 /usr/local/bin，并赋予执行权限：/usr/local/bin/$script_name_no_ext"
    done
}

# 显示进度条
show_progress() {
    local duration=$1
    local interval=0.1
    local total_steps=$(bc <<< "$duration / $interval")

    for ((i=0; i<total_steps; i++)); do
        printf "."
        sleep $interval
    done
    printf "\n"
}

main() {
    install_required_tools

    log "开始下载并执行脚本..."
    download_and_execute_scripts

    log "脚本执行完毕。"
}

main
